import uuid

from math import sqrt
import random

from django.db.models import Q
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, FileResponse, Http404
from django.utils import timezone
from django.views.decorators.http import require_GET, require_POST

from utils.auth import c2s, already_authorized
from xinfou1 import settings
from django.views import View, generic
import json
import utils.response
from utils.response import wrap_json_response, CommonResponseMixin, ReturnCode
from app01.models import User, UserInterest, Interest, UserLanguage, Match, UserStamp, Letter, Stamp
from utils import utils
from django_redis import get_redis_connection

'''
    json.load() # 将一个存储在文件中的json对象（str）转化为相对应的python对象
    json.loads() # 将一个json对象（str）转化为相对应的python对象
    json.dump() # 将python的对象转化为对应的json对象（str),并存放在文件中
    json.dumps() # 将python的对象转化为对应的json对象（str)
'''


# Create your views here.
# 测试session 连接
def test_session(request):
    request.session['message'] = 'Test Django OK'
    response = wrap_json_response(code=ReturnCode.SUCCESS)
    return JsonResponse(data=response, safe=False)


# 认证
def __authorize_by_code(request):
    '''
    使用wx.login得到临时code 到微信提供的code2session接口授权
    post_data{
        'encryptedDate':'xxxx',
        'appId': 'xxx',
        'SessionKey': 'xxx'
        'iv': 'xxx'
    }
    '''
    response = {}
    # 解码utf-8
    post_data = request.body.decode()
    post_data = json.loads(post_data)
    app_id = post_data.get('appId')
    nickname = post_data.get('nickname')
    code = post_data.get('code')
    image_url = post_data.get('image_url')
    province = post_data.get('province')
    city = post_data.get('city')
    sex = post_data.get('sex')

    print(code, app_id)
    if not (app_id and code):
        response['code'] = ReturnCode.BROKEN_AUTHORIZED_DATA
        response['message'] = 'authorized failed. need entire authorization data.'
        return JsonResponse(response, safe=False)

    try:
        data = c2s(app_id, code)
    except Exception as e:
        print(e)
        response['code'] = ReturnCode.FAILED
        response['message'] = 'authorized error.'
        return JsonResponse(response, safe=False)
    open_id = data.get('openid')
    if not open_id:
        response['code'] = ReturnCode.FAILED
        response['message'] = 'authorized error'
        return JsonResponse(response, safe=False)
    request.session['openid'] = open_id
    request.session['is_authorized'] = True

    # 随机获取三个邮票
    stampList = Stamp.objects.all()
    print(stampList)
    stampIdList = [x.id for x in stampList]
    print(stampIdList)
    # 保证不一样
    random.shuffle(stampIdList)
    print(stampIdList)
    one = stampIdList[0]
    two = stampIdList[1]
    three = stampIdList[2]

    print(open_id)
    # User.objects.get(open_id=open_id)
    # 不要用get，用get查询如果结果数量 !=1 就会抛异常
    # 如果用户不存在，则新建用户

    if not User.objects.filter(open_id=open_id):
        own_id = utils.get_short_id()
        new_user = User(user_id=own_id, open_id=open_id, nickname=nickname, image_url=image_url, province=province,
                        city=city, sex=sex, receive=0, post=0, birthday=timezone.now())
        # need to do
        own_id = new_user.user_id
        new_user.save()

        new_stamp1 = UserStamp(user_id=own_id, stamp_id=one, mount=1)
        new_stamp2 = UserStamp(user_id=own_id, stamp_id=two, mount=1)
        new_stamp3 = UserStamp(user_id=own_id, stamp_id=three, mount=1)

        # need to do
        new_interest = UserInterest(user_id=own_id, interest_id=1)
        UserInterest.save(new_interest)

        user_language = UserLanguage(user_id=own_id, language_id=1, proficiency=1)
        user_language.save()

        get_match = Match(user_id=own_id, max_age=100, min_age=1, auto_match=True)
        get_match.save()

        new_stamp1.save()
        new_stamp2.save()
        new_stamp3.save()

    else:
        user = User.objects.get(open_id=open_id)
        user.sex = sex
        user.nickname = nickname
        user.image_url = image_url
        user.province = province
        user.city = city
        user.save()
        own_id = user.user_id
        userid = user.user_id
        userStamp1 = UserStamp.objects.filter(user_id=userid, stamp_id=one)

        if len(userStamp1) != 0:
            mount = [x.mount for x in userStamp1]
            user1 = [x for x in userStamp1]
            user1 = user1[0]
            user1.mount = mount[0] + 1
            user1.save()
        else:
            UserStamp.objects.create(user_id=userid, stamp_id=one, mount=1)
        userStamp2 = UserStamp.objects.filter(user_id=userid, stamp_id=two)
        if len(userStamp2) != 0:
            mount = [x.mount for x in userStamp2]
            user2 = [x for x in userStamp2]
            user2 = user2[0]
            user2.mount = mount[0] + 1
            user2.save()
        else:
            UserStamp.objects.create(user_id=userid, stamp_id=two, mount=1)
        userStamp3 = UserStamp.objects.filter(user_id=userid, stamp_id=three)
        if len(userStamp3) != 0:
            mount = [x.mount for x in userStamp3]
            user3 = [x for x in userStamp3]
            user3 = user3[0]
            user3.mount = mount[0] + 1
            user3.save()
        else:
            UserStamp.objects.create(user_id=userid, stamp_id=three, mount=1)

    message = 'user authorized successfully'
    session_key = data.get('session_key')

    # cache.set(session_key, own_id, 60 * 60)

    conn = get_redis_connection('default')
    conn.set(session_key, str(own_id), 60 * 60 * 24 * 1)

    response = wrap_json_response(data={'session_key': session_key,
                                        'user_id': own_id}, code=ReturnCode.SUCCESS, message=message)
    return JsonResponse(response, safe=False)


def authenticate(request):
    if 'HTTP_SKEY' in request.META:
        skey = request.META['HTTP_SKEY']
        conn = get_redis_connection('default')
        if conn.exists(skey):
            user_id = conn.get(skey)
            data = {'user_id': user_id}
            response = {'code': '0',
                        'msg':'判断是否在http请求中',
                        'data': data,
                        }
            return JsonResponse(data=response, safe=False)
        else:
            data = {'msg': 'skey过期',
                    'code': '1'}
            return JsonResponse(data=data, safe=False)
    else:
        data = {'msg': '缺少skey',
                'code': '1'}
        return JsonResponse(data=data, safe=False)


# 判断是否已经登陆
def get_status(request):
    print('call get_status function...')
    if already_authorized(request):
        data = {"is_authorized": 1}
    else:
        data = {"is_authorized": 0}
    response = CommonResponseMixin.wrap_json_response(data=data, code=ReturnCode.SUCCESS)
    return JsonResponse(response, safe=False)


# 去认证
def authorize(request):
    return __authorize_by_code(request)


# 登出
def logout(request):
    '''
    注销，小程序删除存储的Cookies
    '''
    request.session.clear()
    response = {}
    response['result_code'] = 0
    response['message'] = 'logout success.'
    return JsonResponse(response, safe=False)


# 更新生日(同时更新星座)
@require_POST
def update_birthday(request):
    require = ['user_id', 'birthday']

    if utils.parameters_judge(require, request.POST.keys()):
        user = User.objects.filter(user_id=request.POST.get('user_id'))
        if user.count() == 0:
            return JsonResponse(utils.user_missing())
        user = user[0]
        print(type(request.POST.get('birthday')))
        user.birthday = request.POST.get('birthday')
        print(type(user.birthday))
        user.save()



        return JsonResponse(utils.get_response(0, '更新生日', None))
    else:
        return JsonResponse(utils.parameters_missing())


# 获取生日(如果生日为空 code返回1 data为null)
def get_birthday(request):
    response = {}
    user_id = request.GET.get('user_id')

    # 如果用户不存在，则新建用户
    if not User.objects.filter(user_id=user_id):
        response['code'] = 1
        response['message'] = '不存在此用户'
        return JsonResponse(response, safe=False)

    user = User.objects.get(user_id=user_id)
    response['code'] = 0
    response['message'] = '获取生日'
    birth = [user.birthday.year, user.birthday.month, user.birthday.day]
    data = {'birthday': birth}
    response['data'] = data
    return JsonResponse(response, safe=False)
    pass


# 获取兴趣列表
@require_GET
def get_interest_list(request):
    require = ['user_id']
    if utils.parameters_judge(require, request.GET.keys()):
        user = User.objects.filter(user_id=request.GET.get('user_id'))
        if user.count() == 0:
            return JsonResponse(utils.user_missing())
        user = user[0]
        interests = list(UserInterest.objects.filter(user=user).values('interest__name'))
        data = []
        for inte in interests:
            data.append(inte.get('interest__name'))
        return JsonResponse(utils.get_response(0, '获取兴趣列表', data))
    else:
        return JsonResponse(utils.parameters_missing())

# 更新兴趣列表
def update_interest_list(request):
    response = {}

    post_data = request.body.decode()
    post_data = eval(post_data)
    user_id = post_data.get('user_id')
    interests = post_data.get('interests')
    print(type(interests))
    print(interests)
    all_interests = Interest.objects.all()
    all_interests = [x.name for x in all_interests]
    need_to_add = []
    # 需要删除原来有的
    UserInterest.objects.filter(user_id=user_id).delete()
    # 增加新有的
    # 把对应的爱好全部转为id
    for single in interests:
        user_interest = UserInterest(user_id=user_id, interest_id=single)
        user_interest.save()

    response['code'] = 0
    response['message'] = '兴趣列表更新'

    return JsonResponse(response, safe=False)


# 获取语言及熟练度（熟练度分为 1 2 3三个等级）
@require_GET
def get_language_level(request):
    require = ['user_id']
    if utils.parameters_judge(require, request.GET.keys()):
        user = User.objects.filter(user_id=request.GET.get('user_id'))
        if user.count() == 0:
            return JsonResponse(utils.user_missing())

        user_id = request.GET.get('user_id')
        languages = UserLanguage.objects.filter(user__user_id=user_id).values('language_id', 'proficiency')
        # languages[i] 为 dict
        datas = []
        for lang in languages:
            # objects get 方法返回的是一个对象，直接调用.方法获取值，不用values
            # name = Language.objects.get(id=lang.get('language_id')).name
            data = {
                'language_id': lang.get('language_id'),
                'proficiency': lang.get('proficiency')
            }
            datas.append(data)
        return JsonResponse(utils.get_response(0, '获取语言及熟练度', datas))

    else:
        return JsonResponse(utils.parameters_missing())


# 更新语言及熟练度
@require_POST
def update_language_level(request):
    require = ['user_id', 'languages']
    # 这样request为dict格式
    request = json.loads(request.body)
    if utils.parameters_judge(require, request.keys()):
        user_id = request.get('user_id')
        user = User.objects.filter(user_id=user_id)
        if user.count == 0:
            return JsonResponse(utils.user_missing())

        user = user[0]
        language_list = request.get('languages')  # list
        UserLanguage.objects.filter(user=user).delete()
        for lan in language_list:
            new_lan = UserLanguage(user=user, language_id=lan.get('language_id'), proficiency=lan.get('proficiency'))
            new_lan.save()

        # # save()时会出现 错误  ValueError: The database backend does not accept 0 as a value for AutoField.
        # # 解决方法：language_id 不得为 0！！！！！
        # # 更新熟练度
        # for lan in language_list:
        #     for old_lan in user_lan_list:
        #         if lan.get('language_id') == old_lan.language_id:
        #             old_lan.proficiency = lan.get('proficiency')
        #             old_lan.save()
        #             language_list.remove(lan)
        #             continue
        # # 新增语言
        # for lan in language_list:
        #     u_l = UserLanguage(user_id=user_id, language_id=lan.get('language_id'), proficiency=lan.get('proficiency'))
        #     u_l.save()

        return JsonResponse(utils.get_response(0, "更新语言及熟练度", None))
    else:
        return JsonResponse(utils.parameters_missing())


# 获取配对设置
@require_GET
def get_match(request):
    require = ['user_id']
    if utils.parameters_judge(require, request.GET.keys()):
        user = User.objects.filter(user_id=request.GET.get('user_id'))
        if user.count() == 0:
            return JsonResponse(utils.user_missing())
        else:
            user = user[0]
            pair_set = Match.objects.get(user=user)
            datas = []
            data = {
                'is_autopair': pair_set.auto_match,
                'min_age': pair_set.min_age,
                'max_age': pair_set.max_age
            }
            datas.append(data)
            return JsonResponse(utils.get_response(0, '获取配对设置', datas))

    else:
        return JsonResponse(utils.parameters_missing())


# 更新配对设置
@require_POST
def update_match(request):
    require = ['user_id', 'is_autopair', 'min_age', 'max_age']
    if utils.parameters_judge(require, request.POST.keys()):
        user = User.objects.filter(user_id=request.POST.get('user_id'))
        if user.count() == 0:
            return JsonResponse(utils.user_missing())
        else:
            user = user[0]
            # todo 每次生成新用户要新创建一个默认的配对设置
            pair_set = Match.objects.get(user=user)
            pair_set.auto_match = request.POST.get('is_autopair')
            pair_set.min_age = request.POST.get('min_age')
            pair_set.max_age = request.POST.get('max_age')
            pair_set.save()
            return JsonResponse(utils.get_response(0, '更新配对设置', None))

    else:
        return JsonResponse(utils.parameters_missing())


# 获取用户所有的邮票id及数量
@require_GET
def get_all_stamp_IdAndNum(request):
    require = ['user_id']
    if utils.parameters_judge(require, request.GET.keys()):
        user = User.objects.filter(user_id=request.GET.get('user_id'))
        if 0 == user.count():
            return JsonResponse(utils.user_missing())
        else:
            user = user[0]
            stamps = UserStamp.objects.filter(user=user).values('stamp__id', 'mount')
            datas = []
            for sta in stamps:
                if sta.get('mount') > 0:
                    data = {
                        'stamp_id': sta.get('stamp__id'),
                        'mount': sta.get('mount')
                    }
                    datas.append(data)
            return JsonResponse(utils.get_response(0, '获取用户所有的邮票id及数量', datas))

    else:
        return JsonResponse(utils.parameters_missing())


# 获取与某个笔友所有信件列表中的笔友信息
@require_GET
def getAllInfoFromFriendsList(request):
    require = ['pal_user_id']
    if utils.parameters_judge(require, request.GET.keys()):
        user = User.objects.filter(user_id=request.GET.get('pal_user_id'))
        if user.count == 0:
            return JsonResponse(utils.user_missing())
        user = user[0]

        # 获取星座
        birth = user.birthday.strftime("%Y-%m-%d").split('-')
        # 转化为 int 类型
        month = int(birth[1])
        day = int(birth[2])
        constellation = utils.constellation_judge(month, day)

        datas = [
            {
                "nickname": user.nickname,
                "icon": user.image_url,
                "birthday": user.birthday,
                "constellation": constellation,
                "province": user.province,
                "city": user.city
            }
        ]
        return JsonResponse(utils.get_response(0, '获取与某个笔友所有信件列表中的笔友信息', datas))
    else:
        return JsonResponse(utils.parameters_missing())


# 获取某个用户的笔友列表
@require_GET
def getFriendsList(request):
    require = ['user_id']
    if utils.parameters_judge(require, request.GET.keys()):
        user = User.objects.filter(user_id=request.GET.get('user_id'))
        if user.count == 0:
            return JsonResponse(utils.user_missing())
        user = user[0]

        now = timezone.now()
        # 获取朋友user_id ，friends_id1为 [{'receive_user__user_id': 2}] 即list里面存字典
        friends_id1 = list(Letter.objects.filter(post_user=user, receive_time__lt=now).values('receive_user__user_id').distinct())
        friends_id2 = list(Letter.objects.filter(receive_user=user, receive_time__lt=now).values('post_user__user_id').distinct())
        ids1 = []
        ids2 = []
        # 遍历List 取出id
        for fri_id in friends_id1:
            ids1.append(fri_id.get('receive_user__user_id'))
        for fri_id in friends_id2:
            ids2.append(fri_id.get('post_user__user_id'))
        # 合并并去重 获得id列表
        ids = list(set(ids1 + ids2))

        datas = []
        for user_id in ids:
            user1 = User.objects.get(user_id=user_id)
            let = list(Letter.objects.filter(Q(post_user=user, receive_user=user1) | Q(post_user=user1, receive_user=user)). \
                       order_by('-receive_time'). \
                       values('receive_time'))
            last_time = let[0].get('receive_time').strftime('%Y-%m-%d-%H-%M').split('-')
            date = [int(last_time[0]), int(last_time[1]), int(last_time[2]), int(last_time[3]),int(last_time[4])]
            data = {
                "nickname": user1.nickname,
                "icon": user1.image_url,
                "province": user1.province,
                "city": user1.city,
                "last_time" : date,
                "pal_user_id" : user1.user_id
            }
            datas.append(data)

        return JsonResponse(utils.get_response(0, '获取该用户的笔友列表', datas))
    else:
        return JsonResponse(utils.parameters_missing())


@require_GET
def pair_info(request):
    require = ['user_id']
    if utils.parameters_judge(require, request.GET.keys()):
        user = User.objects.filter(user_id=request.GET.get('user_id'))
        if user.count == 0:
            return JsonResponse(utils.user_missing())
        user = user[0]

        # 获取星座
        birth = user.birthday.strftime("%Y-%m-%d").split('-')
        # 转化为 int 类型
        month = int(birth[1])
        day = int(birth[2])
        constellation = utils.constellation_judge(month, day)

        # 获取语言列表
        languages = list(UserLanguage.objects.filter(user=user).values('language_id', 'proficiency'))

        # 获取兴趣
        interests = list(UserInterest.objects.filter(user=user).values('interest__id'))
        interest = []
        for inte in interests:
            interest.append(inte.get('interest__id'))

        datas = [
            {
                "nickname": user.nickname,
                "icon": user.image_url,
                "province": user.province,
                "birthday": user.birthday,
                "constellation": constellation,
                "sex": user.sex,
                "city": user.city,
                "language": languages,
                "interests": interest,
                "post": user.post,
                "receive": user.receive
            }
        ]
        return JsonResponse(utils.get_response(0, '获取匹配时的笔友详细信息', datas))

    else:
        return JsonResponse(utils.parameters_missing())


# 获取自动匹配时的笔友列表
class LoadData(View, CommonResponseMixin):

    def __init__(self):
        self.data = {}
        datalist = UserInterest.objects.all()
        # print(datalist)
        # 建两个表 user-id : interests
        # 为了形成 user-id : [兴趣列表]   1:[1,2,3] 2:[2,3]
        for x in datalist:
            if x.user.user_id not in self.data.keys():
                self.data[x.user.user_id] = [x.interest.id]
            else:
                self.data[x.user.user_id].append(x.interest.id)
        print(self.data)

    # 计算相似度 返回的值越小 它就相似度越高
    def Education(self, user1, user2):
        user1_data = self.data[user1]
        user2_data = self.data[user2]
        distance = 0
        # 1:[1,2,3]
        # user1_data里面全部都是兴趣了 [1,2,3]
        for x in user1_data:
            if x in user2_data:
                # distance越大越相似
                distance += 1

        return 1 / (1 + sqrt(distance))

    # 根据两个user_id,找共同兴趣
    def getsame(self, user1id, user2id):
        datalist = []
        allinterest = []
        interestlist = Interest.objects.all()
        for single in interestlist:
            allinterest.append(single.name)
        # print(interestlist)
        list1 = UserInterest.objects.filter(user_id=user1id)
        list2 = UserInterest.objects.filter(user_id=user2id)
        for single in list1:
            # print(single.interest.id)
            for single2 in list2:
                if single.interest.id == single2.interest.id:
                    datalist.append(allinterest[single.interest.id])

        return datalist

    def judge_commen_language(self, user1, user2):
        # 找到这两个对应的user_language对象
        user1 = UserLanguage.objects.filter(user_id=user1)
        user2 = UserLanguage.objects.filter(user_id=user2)
        user2 = [x.language.id for x in user2]
        # 如果user1中的一个语言在user2中也存在那么返回1
        languageList = []
        for x in user1:
            if x.language.id in user2:
                languageList.append(x.language.name)
        # 否则返回0
        return languageList

    # 排除已经有了的朋友
    def get_friends(self, userid):
        # 找出所有他发的邮件的对象
        friendsList1 = Letter.objects.filter(post_user=userid)
        # 找出所有发他的对象
        friendsList2 = Letter.objects.filter(receive_user=userid)
        friendsList = [x.receive_user.user_id for x in friendsList1]
        for x in friendsList2:
            friendsList.append(x.post_user.user_id)
        # 去重
        friendsList = list(set(friendsList))

        return friendsList

    # 主要的get方法
    def get(self, request):
        response = {}
        data = []
        res = []
        userId = request.GET.get('user_id')
        get_match_object = Match.objects.get(user_id=userId)
        if get_match_object.auto_match == False:
            response['code'] = 1
            response['messgae'] = '不接受自动匹配'
            return JsonResponse(response, safe=False)
        max_age = get_match_object.max_age
        min_age = get_match_object.min_age
        print(userId)
        for user_id in self.data.keys():
            # 排除与自己计算相似度
            if user_id != userId:
                similar = self.Education(userId, user_id)
                # tuple
                res.append((user_id, similar))
        # 由低往高排 越高相关性越低 一次推荐15个 根据得分排序 (user_id,score)
        res.sort(key=lambda val: val[1])
        # 后续的话可以加
        res = res[0:20]

        print(res)
        # 用于存取从20个中拿去的index
        totalIndex = []
        friend_list = self.get_friends(userId)
        i = 0
        for x in res:
            temp = {}
            commen_language = []
            common_interests = []
            user = User.objects.get(user_id=x[0])
            # 如果没有共同语言直接pass
            # 如果已经是朋友了也直接pass
            commen_language = self.judge_commen_language(userId, user.user_id)
            user_age = utils.getAge(timezone.now(), user.birthday)
            print(commen_language)
            if user.user_id in friend_list:
                continue
            if len(commen_language) != 0 and max_age >= user_age >= min_age:
                temp['pal_user_id'] = user.user_id
                temp['nick_name'] = user.nickname
                temp['icon'] = user.image_url
                temp['province'] = user.province
                temp['city'] = user.city
                common_interests = self.getsame(userId, user.user_id)
                temp['common_interests'] = common_interests
                temp['language'] = commen_language
                data.append(temp)

                totalIndex.append(i)
                i += 1
            if len(totalIndex) == 6:
                break

        # 如果查询到的小于6  但是所有的用户集合结果大于6
        # 根据index来判断 这个是否已经访问过 并添加了
        i = 0
        if len(totalIndex) <= 6 and len(res) >= 6:
            for x in res:
                if user.user_id in friend_list:
                    continue
                if i not in totalIndex:
                    temp = {}
                    user = User.objects.get(user_id=x[0])
                    temp['pal_user_id'] = user.user_id
                    temp['nick_name'] = user.nickname
                    temp['icon'] = user.image_url
                    temp['province'] = user.province
                    temp['city'] = user.city
                    common_interests = self.getsame(userId, user.user_id)
                    commen_language = self.judge_commen_language(userId, user.user_id)
                    temp['common_interests'] = common_interests
                    temp['language'] = commen_language

                    data.append(temp)
                    i += 1

        response['code'] = 0
        response['message'] = '获取自动匹配时的笔友列表'
        response['data'] = data
        return JsonResponse(response, safe=False)



# userView
class UserInfo(View, CommonResponseMixin):
    def get(self, request):
        # 如果没有认证
        # if not already_authorized(request):
        #     response = self.wrap_json_response(ReturnCode.UNAUTHORIZED)
        #     return JsonResponse(response, safe=False)
        # open_id = request.session.get('open_id')
        # 测试用2
        # open_id = 2

        user_id = request.GET.get('user_id')
        print(user_id)
        user = User.objects.get(user_id=user_id)

        print(user)

        # 获取星座
        birth = user.birthday.strftime("%Y-%m-%d").split('-')
        # 转化为 int 类型
        year = int(birth[0])
        month = int(birth[1])
        day = int(birth[2])
        constellation = utils.constellation_judge(month, day)

        data = {'nickname': user.nickname, 'sex': user.sex, 'icon': user.image_url, 'birthday': [year, month, day],
                'constellation': constellation,
                'province': user.province, 'city': user.city, 'receive': user.receive, 'post': user.post}
        print(data)
        response = CommonResponseMixin.wrap_json_response(data=data, code=ReturnCode.SUCCESS)
        return JsonResponse(response, safe=False)

    # 还未测试
    def post(self, request):
        # 如果没有认证
        if not already_authorized(request):
            response = self.wrap_json_response(ReturnCode.UNAUTHORIZED)
            return JsonResponse(response, safe=False)
        open_id = request.session.get('open_id')
        user = User.objects.get(open_id=open_id)
        # got str object
        receive_body = request.body.decode('utf-8')
        receive_body = eval(receive_body)
        nickname = receive_body.get('nickname')
        sex = receive_body.get('sex')
        icon = receive_body.get('icon')
        # todo生日不能大于当前的日期
        birthday = receive_body.get('birthday')
        constellation = user.constellation
        city = receive_body.get('city')
        receive = receive_body.get('receive')
        post = receive_body.get('post')

        if nickname is None:
            nickname = []
        if sex is None:
            sex = []
        if icon is None:
            icon = []
        if birthday is None:
            birthday = []
        if constellation is None:
            constellation = []
        if city is None:
            city = []
        if receive is None:
            receive = []
        if post is None:
            post = []

        user.nickname = json.dumps(nickname)
        user.sex = json.dumps(sex)
        user.image_url = json.dumps(icon)
        user.birthday = json.dumps(birthday)
        user.province = json.dumps(constellation)
        user.city = json.dumps(city)
        user.receive = json.dumps(receive)
        user.post = json.dumps(post)

        user.save()
        message = 'modify user info success'
        response = CommonResponseMixin.wrap_json_response(code=ReturnCode.SUCCESS, message=message)
        return JsonResponse(response, safe=False)

@require_GET
def delay_time(request):
    require = ['user_id', 'receive_user_id']
    if utils.parameters_judge(require, request.GET.keys()):
        user = User.objects.filter(user_id=request.GET.get('user_id'))
        receive_user = User.objects.filter(user_id=request.GET.get('receive_user_id'))
        if user.count == 0 or receive_user.count == 0 :
            return JsonResponse(utils.user_missing())
        user = user[0]
        receive_user = receive_user[0]
        delay_hour = utils.get_delay_time(user.city, receive_user.city)
        return JsonResponse(utils.get_response(0, '获取延迟时间', delay_hour))

    else:
        return JsonResponse(utils.parameters_missing())













